import { defineStore } from 'pinia'

export const useAiChatStore = defineStore('aiChat', {
    state: () => ({
        messages: JSON.parse(uni.getStorageSync('aiChatHistory') || '[]'),
        sessionId: uni.getStorageSync('aiSessionId') || '',
        showDialog: uni.getStorageSync('aiDialogState') === 'true' || false
    }),

    actions: {
        // 添加新消息
        addMessage(message) {
            this.messages.push(message)
            this.saveMessages()
        },

        // 保存消息到本地存储
        saveMessages() {
            uni.setStorageSync('aiChatHistory', JSON.stringify(this.messages))
        },

        // 设置会话ID
        setSessionId(id) {
            this.sessionId = id
            uni.setStorageSync('aiSessionId', id)
        },

        // 清空对话
        clearMessages() {
            this.messages = []
            this.saveMessages()
        },

        // 显示/隐藏对话框（带持久化）
        toggleDialog(visible) {
            this.showDialog = visible
            uni.setStorageSync('aiDialogState', visible.toString())
            console.log('对话框状态已更新为:', visible)
        }
    },

    getters: {
        isDialogVisible: (state) => state.showDialog
    }
})